<template>
    <el-upload :file-list="fileList"
               list-type="picture-card"
               :limit="6"
               action="#"
               multiple
               :http-request="uploadAction"
               :on-success="handleAvatarSuccess"
               :before-upload="handleBeforeUpload"
               :on-change="handleChange"
               :on-remove="handleRemove"
               :on-exceed="handleExceed"
               :on-preview="handlePreview"
               ref="elUploadRef"
               class="avatar-uploader">
        <el-icon><Plus /></el-icon>
    </el-upload>
    <el-dialog v-model="dialogVisible" width="600px">
        <div style="text-align: center">
            <img :src="dialogImageUrl" style="width: 400px;"/>
        </div>
    </el-dialog>
</template>

<script lang="ts">
    import {ref} from "vue";
    import {ElMessage, ElLoading} from "element-plus";
    import {uploadImage} from "../api";
    import { Plus } from '@element-plus/icons-vue';
    export default {
        name: "ImageUploader",
        emits: ["imageChange"],
        setup(props, context) {
            const fileList = ref([]);
            const imageList = ref([]);
            const dialogImageUrl = ref('');
            const dialogVisible = ref(false);
            // 清除
            const elUploadRef = ref();
            const onClear = () => {
                console.log("onClear");
                elUploadRef.value.clearFiles();
                fileList.value = [];
                imageList.value = [];
            };

            // 初始化（回显）
            const onInitImage = (images) => {
                fileList.value = [];
                imageList.value = [];
                for (let i = 0; i < images.length; i ++) {
                    const url = images[i];
                    fileList.value.push({name: url, url: url, uid: i});
                    imageList.value.push({url: url, uid: i});
                }
            };

            // 图片上传
            const uploadAction = (option) => {
                const loading = ElLoading.service({
                    lock: true,
                    text: '图片上传中...',
                    background: 'rgba(0, 0, 0, 0.7)',
                });
                console.log("uploadAction");
                const f = option.file;
                uploadImage(f).then((res) => {
                    if (res && res.code === 200) {
                        console.log("uploadImage", f, res.data);
                        imageList.value.push({uid: f.uid, url: res.data});
                        // state.fileName = res.data.fileName;
                        // state.bannerUrl = res.data.imageUrl;
                        context.emit('imageChange', imageList.value);
                        ElMessage.success('图片上传成功！');
                    } else {
                        if (res && res.msg) {
                            ElMessage.error(res.msg);
                        } else {
                            ElMessage.error('图片上传失败！');
                        }
                    }
                }).finally(() => {
                    loading.close();
                })

            };

            const handleAvatarSuccess = (res, file) => {
                if (res.code !== 200) {
                    ElMessage.error(res.message);
                    return ;
                }
                imageUrl.value = URL.createObjectURL(file.raw);
                form.url = ref(res.data);
            };

            const handleChange  = (file, files) => {
                console.log("handleChange", file, files);
                // context.emit('imageChange', imageList.value);
            };

            const handleRemove = (file, files) => {
                console.log("handleRemove", file, files);
                imageList.value = imageList.value.filter(item => item.url !== file.url && item.uid !== file.uid);
                context.emit('imageChange', imageList.value);
                console.log("imageList", imageList);
            };

            const handlePreview = (uploadFile) => {
                dialogImageUrl.value = uploadFile.url;
                dialogVisible.value = true
            };

            const handleBeforeUpload = (file) => {
                console.log("handleBeforeUpload", file);
                let typeArray = ['image/jpg', 'image/jpeg', 'image/png', 'image/gif'];
                let typeAllow = typeArray.indexOf(file.type);
                if (typeAllow === -1) {
                    ElMessage.warning('上传头像图片只能是 jpg、jpeg、png或gif格式！');
                    return false;
                }
            };
            const handleExceed = () => {
                ElMessage.warning("最多上传6张");
                return false;
            };

            return {
                fileList,
                dialogImageUrl,
                dialogVisible,
                elUploadRef,
                uploadAction,
                onClear,
                onInitImage,
                handleAvatarSuccess,
                handleBeforeUpload,
                handleChange,
                handleRemove,
                handlePreview,
                handleExceed,
            };
        },
    }
</script>

<style scoped>
    .avatar-uploader ::v-deep(.el-upload){
        width: 146px;
        height: 146px;
        line-height: 146px;
    }
</style>